package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JinMaoUtil;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantThirdBaseInfo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author hekelong
 * @date 2025/11/11 16:21
 */
@Service
public class JinMaoApisMaskService implements IPushApiService, IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String orderNum = UUID.randomUUID().toString();

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMask = memberSourceInfo.getMobileMask();
        if (StringUtils.isEmpty(mobileMask)) {
            pushApiResult.setCode("301" );
            pushApiResult.setMessage("掩码不存在,不进行撞库" );
            return pushApiResult;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());
        paramMap.put("mobilePrefix8", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("userName", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1) {
            paramMap.put("sex", 1);
        } else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age", memberSourceInfo.getAge());
        String timestamp = String.valueOf(System.currentTimeMillis());
        paramMap.put("requestId", timestamp);
        paramMap.put("provinceName", memberSourceInfo.getProvince());
        String cityName = memberSourceInfo.getCity();
        if (StringUtils.isNotEmpty(cityName) && cityName.endsWith("市" )) {
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        paramMap.put("cityName", cityName);
        paramMap.put("sesameSeed", JinMaoUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("huabei", JinMaoUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("whiteStripe", JinMaoUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        paramMap.put("overdueSituation", JinMaoUtil.getYuQi(memberSourceInfo.getYuqi()));
        paramMap.put("loanLimit", JinMaoUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("education", JinMaoUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("socialSecurity", JinMaoUtil.getSheBao(memberSourceInfo.getShebao()));
        paramMap.put("creditCard", JinMaoUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        paramMap.put("occupation", JinMaoUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("accumulation", JinMaoUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", JinMaoUtil.getBaoXian(memberSourceInfo.getBaoxian()));
        paramMap.put("car", JinMaoUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", JinMaoUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("regIp", memberSourceInfo.getReqIp());

        //加密
        String encrypt = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());
        bizMap.put("data", encrypt);

        log.info("【金猫优选掩码全流程分润】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json" )
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【金猫优选掩码全流程分润】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code" );
        String message = resultObject.getString("message" );


        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (!(code == 0)) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        // 撞库成功之后，商户的机构数据存储
        JSONObject data = resultObject.getJSONObject("data" );

        String logo = data.getString("logo");
        String name = data.getString("productName");
        String orgName = data.getString("companyName");

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("orderNo", orderNum);
        infoObject.put("productId", orderNum);
        infoObject.put("productName", name);
        infoObject.put("companyName", orgName);
        infoObject.put("companyLogo", logo);
        infoObject.put("maxLoanAmount", "200000");
        infoObject.put("maxLoanRate", "20");
        infoObject.put("minLoanRate", "1");
        infoObject.put("businessInfo", name);
        // 替换原来的两行代码
        JSONObject agreementsList = data.getJSONObject("agreementsList");
        JSONArray jsonArray = new JSONArray();
        if (agreementsList != null) {
            for (Map.Entry<String, Object> entry : agreementsList.entrySet()) {
                JSONObject protocolObj = new JSONObject();
                protocolObj.put("protocalName", entry.getKey());
                protocolObj.put("protocalUrl", entry.getValue());
                jsonArray.add(protocolObj);
            }
        }
        infoObject.put("protocalList", jsonArray);

        thirdInfoDTO.setInfoObject(infoObject);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)) {
            BigDecimal price = data.getBigDecimal("price" );//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1) {
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save) {
            pushApiResult.setPushSuccess(true);
        } else {
            pushApiResult.setMessage("保存撞库数据失败" );
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        JSONObject bizMap = new JSONObject();
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("userName", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1) {
            bizMap.put("sex", 1);
        } else {
            bizMap.put("sex", 2);
        }
        bizMap.put("age", memberSourceInfo.getAge());
        String timestamp = String.valueOf(System.currentTimeMillis());
        bizMap.put("requestId", timestamp);
        bizMap.put("provinceName", memberSourceInfo.getProvince());
        String cityName = memberSourceInfo.getCity();
        if (StringUtils.isNotEmpty(cityName) && cityName.endsWith("市" )) {
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        bizMap.put("cityName", cityName);
        bizMap.put("sesameSeed", JinMaoUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("huabei", JinMaoUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("whiteStripe", JinMaoUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("overdueSituation", JinMaoUtil.getYuQi(memberSourceInfo.getYuqi()));
        bizMap.put("loanLimit", JinMaoUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("education", JinMaoUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("socialSecurity", JinMaoUtil.getSheBao(memberSourceInfo.getShebao()));
        bizMap.put("creditCard", JinMaoUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("occupation", JinMaoUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("accumulation", JinMaoUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("insurance", JinMaoUtil.getBaoXian(memberSourceInfo.getBaoxian()));
        bizMap.put("car", JinMaoUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("house", JinMaoUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("regIp", memberSourceInfo.getReqIp());


        MerchantThirdBaseInfo merchantThirdBaseInfo = merchantThirdBaseInfoService.selectEntityByOrderNo(orderNo);
        if (ObjectUtil.isEmpty(merchantThirdBaseInfo)) {
            pushApiResult.setMessage("商户机构数据为空【pushId】" + orderNo);
            return pushApiResult;
        }

        String orderId = extJson.getString("orderId" );
        String orderItemId = extJson.getString("orderItemId" );
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        bizMap.put("agreementUrl", protocolUrl);

        //加密
        String encrypt = encrypt(JSON.toJSONString(bizMap), pushApiKeyParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());//应用编号
        paramMap.put("data", encrypt);//业务参数

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        log.info("【金猫优选掩码全流程分润】导单开始【infoId】{}【infoName】{}【queryUrl】{}【bizMap】{}【paramMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json" )
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【金猫优选掩码全流程分润】导单结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code" );
        String message = resultObject.getString("message" );

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(message);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED" );

        if (StrUtil.equals(String.valueOf(code), "0" )) {
            String status = "000";
            thirdInfoDTO.setRetCode(code + "|" + status);
            thirdInfoDTO.setRetMsg(message + "|" + message);
            if (StrUtil.equals(status, "000" )) {
                thirdInfoDTO.setStatus("SUCCESS" );
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (StrUtil.equals(String.valueOf(code), "0" )) {
            JSONObject respData = resultObject.getJSONObject("respData" );
            String status = "000";
            pushApiResult.setCode(code + "|" + status);
            pushApiResult.setMessage(message + "|" + message);
            if (StrUtil.equals(status, "000" )) {
                //修改时间
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encrypt(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key 为空 null" );
            return null;
        }// 判断 Key 是否为 16 位
        if (sKey.length() != 16) {
            if (sKey.length() != 32) {
                System.out.print("Key 不合法" );
                return null;
            }
        }
        try {
            byte[] raw = sKey.getBytes("utf-8" );
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES" ); // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding" );
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8" )); // 此处使用 BASE64 做转码功能，同时能起到 2 次加密的作用。
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMask = memberSourceInfo.getMobileMask();
        if (StringUtils.isEmpty(mobileMask)) {
            pushApiResult.setCode("301" );
            pushApiResult.setMessage("掩码不存在,不进行撞库" );
            return pushApiResult;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());
        paramMap.put("mobilePrefix8", mobileMask);
        paramMap.put("userName", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1) {
            paramMap.put("sex", 1);
        } else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age", memberSourceInfo.getAge());
        String timestamp = String.valueOf(System.currentTimeMillis());
        paramMap.put("requestId", timestamp);
        paramMap.put("provinceName", memberSourceInfo.getProvince());
        String cityName = memberSourceInfo.getCity();
        if (StringUtils.isNotEmpty(cityName) && cityName.endsWith("市" )) {
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        paramMap.put("cityName", cityName);
        paramMap.put("sesameSeed", JinMaoUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("huabei", JinMaoUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("whiteStripe", JinMaoUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        paramMap.put("overdueSituation", JinMaoUtil.getYuQi(memberSourceInfo.getYuqi()));
        paramMap.put("loanLimit", JinMaoUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("education", JinMaoUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("socialSecurity", JinMaoUtil.getSheBao(memberSourceInfo.getShebao()));
        paramMap.put("creditCard", JinMaoUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        paramMap.put("occupation", JinMaoUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("accumulation", JinMaoUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", JinMaoUtil.getBaoXian(memberSourceInfo.getBaoxian()));
        paramMap.put("car", JinMaoUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", JinMaoUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("regIp", memberSourceInfo.getReqIp());

        //加密
        String encrypt = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());
        bizMap.put("data", encrypt);

        log.info("【金猫优选上游掩码全流程分润】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json" )
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【金猫优选上游掩码全流程分润】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code" );
        String message = resultObject.getString("message" );


        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (!(code == 0)) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        // 撞库成功之后，商户的机构数据存储
        JSONObject data = resultObject.getJSONObject("data" );

        JSONArray md5List = data.getJSONArray("mobileMd5List" );
        pushApiResult.setMd5List(md5List);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setInfoObject(data);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)) {
            BigDecimal price = data.getBigDecimal("price" );//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1) {
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save) {
            pushApiResult.setPushSuccess(true);
        } else {
            pushApiResult.setMessage("保存撞库数据失败" );
        }

        return pushApiResult;
    }
}
